import { ajaxPromiseObject } from "../../../util/interface.js";
import dom, { ajax, domg } from "../../init.js";
import { obj } from "../../index.js";
import event from "./eventhandle.js";
import { initurl } from "../../navigation/eventhandle.js";

//初始化获取文章
export async function initarticle() {
  let str = `
    <div class="articlelist">
      <h2>index: Index</h2>
      <hr>
    </div>
    <ul class="limitlist">
    </ul>`;
  if (dom.content.content) dom.content.content.innerHTML = str;
  const url = "/article/getAllLimit";
  const data = await ajax.get(url, {
    x: String(obj.limit.x),
    y: String(obj.limit.y),
  });
  obj.url = url;
  if (typeof data === "string") {
    const result = JSON.parse(data) as any;
    if (result.data.count && dom.user.articlecount)
      dom.user.articlecount.innerText = result.data.count;
    updateArticleList(result.data.rows);
    updateArticlelimit(result.data.count);
  }
}
//初始化查询标题

export async function initfindetitle() {
  let str = `
    <div class="articlelist">
      <h2>index: Article</h2>
      <hr>
    </div>
    <ul class="limitlist">
    </ul>`;
  if (dom.content.content) dom.content.content.innerHTML = str;
  const data = await ajax.get(obj.url as string, {
    title: String(obj._title),
    x: String(obj.limit.x),
    y: String(obj.limit.y),
  });
  if (typeof data === "string") {
    const result = JSON.parse(data) as any;
    if (result.data.count && dom.user.articlecount)
      dom.user.articlecount.innerText = result.data.count;
    updateArticleList(result.data.rows);
    updateArticlelimit(result.data.count);
  }
}

//根据url设置排序规则
function setz(url: string) {
  const str = url.replace(/\/article\/get/, "");
  if (str === "TimeTop") {
    if (sessionStorage.getItem("timeTop") == "11") {
      return 1;
    } else {
      return 0;
    }
  }
  if (str === "BrowesNumTop") {
    if (sessionStorage.getItem("browesNumTop") == "11") {
      return 1;
    } else {
      return 0;
    }
  }
  return 2;
}
//↓↓↓↓↓↓↓↓↓↓↓
//获取全部文章
export async function getAllLimit(url?: string) {
  if (!url) url = "/article/getAllLimit";
  const data = await ajax.get(url, {
    title: String(obj._title),
    x: String(obj.limit.x),
    y: String(obj.limit.y),
    //判断请求地址是不是排序,如果是就返回排序规则
    z: setz(url),
  });
  if (typeof data === "string") {
    const result = JSON.parse(data) as any;
    if (result.data.count && dom.user.articlecount)
      dom.user.articlecount.innerText = result.data.count;
    updateArticleList(result.data.rows);
    updateArticlelimit(result.data.count);
  }
}

//渲染文章函数
export function updateArticleList(arr: any = []) {
  //重置文章索引
  const top = obj.url === "/article/getTimeTop";
  const bro = obj.url === "/article/getBrowesNumTop";

  if (dom.content.content?.children[0])
    //渲染升序降序
    dom.content.content.children[0].innerHTML = `
      <h2>index: Article</h2>
      ${
        //如果路径是搜索就不显示排序
        obj.url !== "/article/findTitle"
          ? `<h3 id='Top'><span class='timeTop ${
              top ? "istop" : ""
            }'>时间${toppp("timeTop")}</span>
          <span class='browesNumTop ${bro ? "istop" : ""}'>热度${toppp(
              "browesNumTop"
            )}</span></h3>`
          : ""
      }
      <hr>
    `;
  if (domg("#Top")) {
    domg("#Top").onclick = event.Top;
  }
  if (!arr.length && dom.content.content) {
    dom.content.content.children[0].insertAdjacentHTML(
      "beforeend",
      `<div class="nulldata">没有找到数据....</div>`
    );
  }
  let count = 0;
  arr.forEach((item: any, index: any) => {
    count += +item.browesNum;
    const str = `
    <li index=${index} class="list" data-index='${item.id}'>
      <h1 class="title">${item.title}</h1>
      <div class="titles">${item.titles}</div>
      <p>
        <span class="iconfont icon-awardjiangzhang articleauthor">${
          item.author
        }</span>
        <span class="iconfont icon-redu">${item.browesNum}</span>
        <span class="iconfont icon-pinglun articlecommentul">${
          item.ArticleComments.length
        }</span>
        <span class="iconfont icon-bianji">${item.fontlength}</span>
        <span class="iconfont icon-shijian_o">${item.createdTime}</span>
        ${labetstyle(item.label)}
      </p>
      ${/* 如果没有文章则不渲染评论列表 */ ""}
      ${
        item.ArticleComments.length
          ? `<ul class="articlecommentlist">
              ${articlecommentlistmini(item.ArticleComments)}
            </ul>`
          : ""
      }
    </li>`;
    dom.content.content?.children[0]?.insertAdjacentHTML("beforeend", str);
    dom.content.content?.children[0]?.children[
      dom.content.content?.children[0]?.children.length - 1
    ].addEventListener("click", event.articlelist);
  });
  domg(".browesCount").innerText = String(count);
}
//渲染分页
export function updateArticlelimit(num: number) {
  const count = Math.ceil(num / +obj.limit.y);
  if (dom.content.content) {
    let str = "";
    dom.content.content.children[1].innerHTML = "";
    //渲染分页

    //渲染上一页
    if (obj.limit.x != "1") {
      const str = `<li index=${+obj.limit.x - 1}><--</li>`;
      dom.content.content.children[1].insertAdjacentHTML("beforeend", str);
    }
    //渲染中间分页
    for (let i = 1; i <= count; i++) {
      str = `<li index='${i}'>${i}</li>`;
      dom.content.content.children[1].insertAdjacentHTML("beforeend", str);
    }

    //渲染下一页
    if (+obj.limit.x != count) {
      const str = `<li index=${+obj.limit.x + 1}>--></li>`;
      dom.content.content.children[1].insertAdjacentHTML("beforeend", str);
    }
    //绑定事件
    dom.content.content.children[1].addEventListener(
      "click",
      event.articlelimit
    );
    //排他
    const x = +obj.limit.x;
    for (let i = 0; i < dom.content.content.children[1].children.length; i++) {
      dom.content.content.children[1].children[i].classList.remove(
        "articlelimitlist"
      );
    }
    if (dom.content.content.children[1].children[+obj.limit.x])
      dom.content.content.children[1].children[x == 1 ? 0 : x].classList.add(
        "articlelimitlist"
      );
  }
}

function labetstyle(str: string) {
  if (!str) return "";
  if (str === "分享")
    return `<span class="articlelistlabe" style="background-color:#c27ce9">${str}</span>`;
  if (str === "日常")
    return `<span class="articlelistlabe" style="background-color:#d77959">${str}</span>`;
  if (str === "技术")
    return `<span class="articlelistlabe" style="background-color:#42c497">${str}</span>`;
  return `<span class="articlelistlabe" style>${str}</span>`;
}

function articlecommentlistmini(
  arr: Array<{ name: string; createdTime: string; content: string }>
) {
  let str = "";
  arr.forEach((item, index) => {
    str += `
    <a href="#MyArticleComment${index}">
      <p><span>${item.name}</span><span>${item.createdTime}</span></p>
      <p>${item.content}</p>
    </a>`;
  });
  return str;
}

function toppp(str: string): string {
  const item = sessionStorage.getItem(str);
  if (!item || item === "22") {
    return "升序";
  }
  return "降序";
}
